import request from "../../utils/request";

Page({
    data: {
        placement: '',
        hotList: [],
        searchContent: '',
        searchList: [],
        history: []
    },

    onLoad: function (options) {
        this.getSearchDefault();
        this.getHotList();
        this.getHistory();
    },

    async getSearchDefault() {
        const res = await request('/search/default');
        this.setData({placement: res.data.showKeyword});
    },

    async getHotList() {
        const res = await request('/search/hot/detail');
        const hotList = res.data || [];
        hotList.forEach((item, index) => {
            item.id = index;
        });
        this.setData({hotList});
    },

    getHistory() {
        const history = wx.getStorageSync('history') || [];
        this.setData({history});
    },

    //处理input内容改变事件
    handleInputChange(e) {
        const {value} = e.detail;
        if (!value.trim()) {
            this.setData({searchContent: ''});
            return;
        }

        //节流函数
        this.timer && clearTimeout(this.timer);
        this.timer = setTimeout(() => {
            this.setData({searchContent: value.trim()});
            this.getSearchResult(value);
        }, 300);
    },

    async getSearchResult(keywords) {
        const res = await request('/search', {keywords, limit: 20});
        this.setData({searchList: res.result.songs});
        //将搜索关键字加入历史记录中
        const {history} = this.data;
        const index = history.findIndex(item => item === keywords);
        if (index >= 0) {
            history.splice(index, 1);
        }
        history.unshift(keywords);
        this.setData({history});
        wx.setStorageSync('history', history);
    },

    handleSearch(e) {
        const {content} = e.currentTarget.dataset;
        this.setData({searchContent: content});
        this.getSearchResult(content);
    },

    handleCancel() {
        this.setData({searchContent: '', searchList: []});
    },

    handleDelete() {
        wx.showModal({
            title: '提示',
            content: '确认删除历史记录吗？',
            success: (res) => {
                if (res.confirm) {
                    this.setData({history: []});
                    wx.removeStorageSync('history');
                }
            }
        })
    }
});
